package com.ywu.standard.gateway.handler.user;

import com.ywu.boot.config.BootConfigAppConfig;
import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextApp;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.context.YwuContextUser;
import com.ywu.common.constant.CommonConstant;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.result.CommonResult;
import com.ywu.common.utils.AesUtils;
import com.ywu.standard.gateway.handler.user.impl.UserMssaHandlerInterface;
import com.ywu.standard.gateway.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.Map;

/**
 * @ClassName UserTokenMssaHandler
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/9/28 9:47
 * @Version 1.0
 **/
@Component
@Slf4j
@Order(1)
public class UserTokenMssaHandler implements UserMssaHandlerInterface {
    private static final String AUTH_TOKEN_HEADER_KEY = "AuthToken";

    private static final String APP_ID = "appId";

    private static final String APP_TOKEN = "appToken";

    private static final String SOURCE = "source";

    @Autowired
    private BootConfigAppConfig bootConfigAppConfig;

    @Override
    public Object handle(ServerWebExchange exchange) {
        // 获取请求头cookie中的AuthToken
        HttpHeaders headers = exchange.getRequest().getHeaders();
        List<String> authTokenHeaders = (List<String>) headers.get(AUTH_TOKEN_HEADER_KEY);
        if (CollectionUtils.isEmpty(authTokenHeaders)) {
            return CommonResult.error().setCode(CommonConstant.AUTH_TOKEN_EMPTY_ERROR).setErrorCode(CommonConstant.AUTH_TOKEN_EMPTY_MESSAGE)
                    .setMessage("Cookie中的AuthToken字段不存在");
        }
        String authToken = authTokenHeaders.get(0);
        // 解密authToken
        String decryptTokenKey; // 解析tokenKey数据
        try {
            decryptTokenKey = AesUtils.decrypt(bootConfigAppConfig.getTokenKey(), bootConfigAppConfig.getSecretKey());
        } catch (Exception e) {
            log.error("UserTokenMssaHandler decrypt token key error {}", e.getMessage());
            return CommonResult.error().setCode(CommonConstant.AUTH_TOKEN_DECRYPT_TOKEN_KEY_ERROR)
                    .setErrorCode(CommonConstant.AUTH_TOKEN_DECRYPT_TOKEN_KEY_MESSAGE)
                    .setMessage("tokenKey解密异常!");
        }
        Map<String, String> tokenInfoMap = JwtUtils.decodeToken(authToken, decryptTokenKey);
        // 获取所有token中的信息
        String appId = tokenInfoMap.get(APP_ID);
        String appToken = tokenInfoMap.get(APP_TOKEN);
        String source = tokenInfoMap.get(SOURCE);
        if (StringUtils.isAnyBlank(appId, appToken, source)) {
            return CommonResult.error().setCode(CommonConstant.AUTH_TOKEN_INFO_ERROR)
                    .setErrorCode(CommonConstant.AUTH_TOKEN_INFO_MESSAGE)
                    .setMessage("token信息异常!");
        }
        // 构建上下文
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        YwuContextUser ywuContextUser = new YwuContextUser();
        ywuContextUser.setUserAccount(appId);
        currentContext.setYwuContextUser(ywuContextUser);
        YwuContextApp ywuContextApp = new YwuContextApp();
        ywuContextApp.setAppId(appId);
        ywuContextApp.setAppToken(appToken);
        ywuContextApp.setSource(source);
        currentContext.setYwuContextApp(ywuContextApp);
        return exchange;
    }
}
